<template>
  <div class="vm">
    <h2 class="h-title">清除图层</h2>
    <div class="tools-x">
      <select id="type" v-model="tool">
        <option v-for="item in tools" :key="item.value" :value="item.value">
          {{ item.label }}
        </option>
      </select>
    </div>
    <div ref="map" class="map-x"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import Draw from "ol/interaction/Draw";
import GeoJSON from "ol/format/GeoJSON";
import { Style, Text, Stroke, Fill, Circle } from "ol/style";
export default {
  data() {
    return {
      tool: "Polygon", // 当前选中的工具
      tools: [
        // 工具集
        {
          value: "Point",
          label: "点",
        },
        {
          value: "LineString",
          label: "线",
        },
        {
          value: "Polygon",
          label: "多边形",
        },
        {
          value: "Circle",
          label: "圆",
        },
        {
          value: "None",
          label: "无",
        },
      ],
      className: "temporary",
      map: null, // 地图
      draw: null,
      source: new SourceVector({
        wrapX: false, // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
      }),
    };
  },
  watch: {
    tool(newVal) {
      this.addInteraction();
    },
  },
  methods: {
    initMap() {
      let raster = new Tile({
        source: new OSM(),
      });
      this.map = new Map({
        target: this.$refs.map,
        layers: [raster],
        view: new View({
          projection: "EPSG:4326",
          center: [113.1206, 23.034996],
          zoom: 10,
        }),
      });
    },
    addInteraction() {
      let layer = new LayerVector({
        source: this.source,
        className: this.className,
      });
      this.map.addLayer(layer);
      this.draw = new Draw({
        source: this.source,
        type: this.tool,
        // 绘制后填充的颜色
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 0, 0, 0.2)",
          }),
          stroke: new Stroke({
            color: "rgba(255, 0, 0, 1)",
            width: 2,
          }),
          image: new Circle({
            radius: 7,
            fill: new Fill({
              color: "rgba(255, 0, 0, 1)",
            }),
          }),
        }),
      });
      this.map.addInteraction(this.draw);
      this.draw.on("drawend", (evt) => {
        this.map.removeInteraction(this.draw);
      });
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>

<style>
</style>